package org.smartboot.sosa.core.module.security;

import java.security.MessageDigest;

/**
 * @author Seer
 * @version Md5.java, v 0.1 2015年10月2日 下午9:55:18 Seer Exp.
 */
public final class Md5 {
	private Md5() {

	}

	/**
	 * 字符参数
	 * 
	 * @param s
	 *            字符参数
	 * @return string 编码
	 */
	public static String mD5(String s) {
		final int m = 2;
		final int n = 4;
		final int a = 0xf;
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

		try {
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char[] str = new char[j * m];
			int k = 0;
			byte byte0 = 0;
			for (int i = 0; i < j; i++) {
				byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> n & a];
				str[k++] = hexDigits[byte0 & a];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取16位的MD5密文
	 * 
	 * @param encryString
	 *            需要加密的字符串
	 * @return 加密后的字符串
	 */
	public static String bit16MD5(String encryString) {
		final int p = 9;
		final int q = 24;
		if (null == encryString) {
			return "";
		} else {
			String bit32 = Md5.mD5(encryString);
			return bit32.substring(p, q);
		}
	}
}